﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Web.SessionState;
using NetWing.BPM.Core;
using NetWing.Common;
using NetWing.BPM.Core.Bll;
using NetWing.BPM.Core.Model;
using Omu.ValueInjecter;
using NetWing.Common.Data;
using NetWing.Common.Data.SqlServer;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Excel;
using NetWing.Common.IO;
using NetWing.Common.IO.DirFile;

namespace NetWing.BPM.Admin.sys.ashx
{
    /// <summary>
    /// UploadHandler 的摘要说明
    /// </summary>
    public class UploadHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            SaveFile("~/upload/system/", context);//上传文件
            //context.Response.Write("Hello World");
        }
        /// <summary>
        /// 文件保存操作
        /// </summary>
        /// <param name="basePath"></param>
        private void SaveFile(string basePath, HttpContext context)
        {
            var name = string.Empty;
            basePath = (basePath.IndexOf("~") > -1) ? context.Server.MapPath(basePath) :
            basePath;
            HttpFileCollection files = context.Request.Files;
            if (!Directory.Exists(basePath))//如果文件夹不存在创建文件夹
                Directory.CreateDirectory(basePath);

            var suffix = files[0].ContentType.Split('/');
            var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1];
            var _temp = System.Web.HttpContext.Current.Request["name"];
            var fname = System.Web.HttpContext.Current.Request["fname"];//自定义文件名上传
            if (!string.IsNullOrEmpty(_temp))
            {
                name = _temp;
            }
            else
            {
                Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                name = rand.Next() + "." + _suffix;
            }
            //假如自定义文件名上传
            if (!string.IsNullOrEmpty(fname))
            {
                name = fname;
            }

            var full = basePath + name;
            files[0].SaveAs(full);
            var _result = "";
            _result = "{\"msg\" : \"文件上传成功!\", \"result\" : \"true\", \"filename\" : \"" + name + "\"}";
            System.Web.HttpContext.Current.Response.Write(_result);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}